package com.ly.cloud.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.plugins.Page;
import com.ly.cloud.dto.QueryLogDto;
import com.ly.cloud.dto.SysLogDto;
import com.ly.cloud.entity.SysLogPo;
import com.ly.cloud.exception.CloudException;
import com.ly.cloud.exception.mapper.DBException;
import com.ly.cloud.mapper.SysLogMapper;
import com.ly.cloud.service.SysLogService;
import com.ly.cloud.utils.IpUtils;
import com.ly.cloud.vo.SysLogVo;

/** 
 * Class Name: SysLogServiceImpl  
 * Description: 
 * @author: LuHuaCong
 * @mail: luhaucong@ly-sky.com 
 * @date: 2018年12月7日
 * @version: 1.0
 *
 */
@Service
@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
public class SysLogServiceImpl implements SysLogService {

	@Autowired
	private SysLogMapper sysLogMapper;
	/**(non-Javadoc)
	 * Title: selectSystemSetList
	 * Description: 
	 * 插入一条日志记录
	 * Created On: 2018年12月7日
	 * @author LuHuaCong
	 * <p>
	 * @param sysLogDto 日志参数封装类
	 * @param request http请求
	 * @return  boolean
	 */
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	@Override
	public boolean insertLog(SysLogDto sysLogDto) {
		
		SysLogPo sysLogPo = new SysLogPo();
		/**
		 * sysLogDto赋值到sysLogPo
		 */
		BeanUtils.copyProperties(sysLogDto, sysLogPo);
		
		/**
		 * 获取客户端的ip地址
		 */		
		sysLogPo.setIp(IpUtils.getIp());
		sysLogPo.setAppTime(new Date());
		
		Integer i;
		try {
			i = sysLogMapper.insert(sysLogPo);
			if(i>0) {
				return true;
			}else {
				return false;
			}
		} catch (Exception e) {
			throw new DBException("添加日志失败！", e);
		}
	}
	
	/** 
	 * Method Name:  selectLogList
	 * Description:  根据条件查询日志记录列表
	 * @param page 
	 * @param appName 操作人
	 * @param startTime 起始时间
	 * @param endTime 结束时间
	 * @return List<SysLogVo>
	 * @exception 	
	 * @author LuHuaCong
	 * @mail luhuacong@ly-sky.com
	 * @date: 2018年12月7日
	 */
	@Override
	public Page<SysLogVo> selectLogList(Page<SysLogVo> page, QueryLogDto dto) {

		
		SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd"); 
		try {
			if(dto.getStartTimeStr()!=null) {
				dto.setStartTime(formatter.parse(dto.getStartTimeStr()));				
			}
			if(dto.getEndTimeStr()!=null) {
				dto.setEndTime(formatter.parse(dto.getEndTimeStr()));
			}
			
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		try {
			Page<SysLogVo> records = page.setRecords(sysLogMapper.selectLogList(page, dto));
			return records;
		} catch (Exception e) {
			e.printStackTrace();
			throw new CloudException("查询异常，请重试!", e);
		}
	}

}
